require('dotenv').config();
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const mongoose = require('mongoose');
const schema = require('./graphql/schema');
const resolvers = require('./graphql/resolvers');
const auth = require('./middleware/auth');
const connectDB = require('./config/database');

// 连接数据库
connectDB();

const app = express();

// GraphQL 中间件
app.use('/graphql', graphqlHTTP(async (req) => ({
    schema: schema,
    rootValue: resolvers,
    graphiql: true,
    context: {
        user: await auth(req)
    }
})));

// 启动服务器
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}/graphql`);
});

// 处理未捕获的异常
process.on('unhandledRejection', (err) => {
    console.log('UNHANDLED REJECTION! 💥 Shutting down...');
    console.log(err.name, err.message);
    process.exit(1);
});